package com.ziyun.pop.web.modules.supp.controller;

import com.service.ucenter.api.VerifyCodeService;
import com.service.ucenter.constant.UcenterResult;
import com.service.ucenter.model.verify.VerifyCodeDto;
import com.utility.JsonUtils;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.storeMember.service.StoreMemberService;
import com.ziyun.pop.modules.supp.dto.SellerCopyGoodsDto;
import com.ziyun.pop.modules.supp.dto.SellerInfoAuditDto;
import com.ziyun.pop.modules.supp.dto.SellerRegisterDto;
import com.ziyun.pop.modules.supp.dto.SellerVerifyCodeDto;
import com.ziyun.pop.modules.supp.entity.SellerInfoEntity;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import com.ziyun.pop.modules.supp.vo.CustomVo;
import com.ziyun.pop.modules.supp.vo.SalesVo;
import com.ziyun.pop.modules.supp.vo.SellerInfoVo;
import com.ziyun.pop.modules.supp.vo.SellerShipVo;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 入驻商户
 * @author gaosheng
 * @date 2018-10-12 13:27
 */
@Slf4j
@RestController
@RequestMapping("supp/sellerinfo")
public class SellerInfoController {

    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private VerifyCodeService verifyCodeService;
    @Autowired
    private StoreMemberService storeMemberService;

    /**
     * 添加子商户
     * @return
     */
    @RequestMapping("/saveSubSellerInfo")
    public R saveSubSellerInfo(@Valid @RequestBody SellerRegisterDto sellerRegisterDto){
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        sellerRegisterDto.setSellerId(sellerId);
        sellerRegisterDto.setMainSellerId(sellerId);
        return sellerInfoService.saveSubSellerInfo(sellerRegisterDto);
    }

    /**
     * 查询子公司信息
     * @return
     */
    @RequestMapping("/querySubSeller")
    public R querySubSeller(@RequestParam Map<String, Object> params){
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        params.put("sellerId", sellerId);
        return sellerInfoService.queryPageSubSellerList(params);
    }

    /**
     * 获取验证码
     */
    @RequestMapping("/queryVerifyCode")
    public R queryVerifyCode(@RequestBody SellerVerifyCodeDto sellerVerifyCodeDto) throws Exception {
        log.info("=================seller verify code api start: " + UserUtils.getCurentUser().getUserId() + "," + UserUtils.getCurentUser().getUsername());
        VerifyCodeDto verifyCodeDto = new VerifyCodeDto();
        verifyCodeDto.setMobile(sellerVerifyCodeDto.getMobile());
        verifyCodeDto.setAliSessionId(sellerVerifyCodeDto.getAliSessionId());
        verifyCodeDto.setAliToken(sellerVerifyCodeDto.getAliToken());
        verifyCodeDto.setAliSig(sellerVerifyCodeDto.getAliSig());
        verifyCodeDto.setAliScene(sellerVerifyCodeDto.getAliScene());
        verifyCodeDto.setIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));

        log.info("=================seller verify code api param:" + JsonUtils.object2String(verifyCodeDto));
        UcenterResult<?> ucenterResult = verifyCodeService.getVerifyCodeValidation(verifyCodeDto);
        log.info("=================seller verify code api result:" + JsonUtils.object2String(ucenterResult));
        int code = ucenterResult.getCode();
        if (code != 1){
            String message = ucenterResult.getMessage();
            if (code == 999){
                log.error("=================seller verify code api error:" + message);
                return R.error("短信服务异常，请联系后台管理员");
            }
            return R.error(message);
        }

        return R.ok();
    }

    /**
     * 验证验证码
     * @param sellerMobile
     * @param verifyCode
     * @return
     */
    @RequestMapping("/checkVerifyCode")
    public R checkVerifyCode(@RequestParam("sellerMobile") String sellerMobile, @RequestParam("verifyCode") String verifyCode){
        return sellerInfoService.checkVerifyCode(sellerMobile, verifyCode);
    }

    /**
     * 查询商户首页信息
     * @return
     */
    @RequestMapping("/querySellerInfo")
    public R querySellerInfo(){
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        Map<String,Object> data = new HashMap<>();
        // 商户资料
        SellerInfoVo sellerInfoVo = sellerInfoService.querySellerInfo(sellerId);
        int onlineCount = storeMemberService.onlineCount(sellerId.intValue());
        int offlineCount = storeMemberService.offlineCount(sellerId.intValue());
        // 总客户
        int totalCustomer = onlineCount + offlineCount;
        // 复购率
        int repeatBuy = storeMemberService.repeatBuy(sellerId.intValue());
        BigDecimal rePurchaseRate = BigDecimal.ZERO;
        if (totalCustomer > 0){
            rePurchaseRate = BigDecimal.valueOf(repeatBuy).divide(new BigDecimal(totalCustomer), 4, BigDecimal.ROUND_HALF_UP);
        }
        String rate = rePurchaseRate.multiply(BigDecimal.valueOf(100)).stripTrailingZeros().toPlainString() + "%";
        sellerInfoVo.setRePurchaseRate(rate);
        sellerInfoVo.setTotalMember(totalCustomer);
        data.put("sellerInfoVo",sellerInfoVo);
        // 近七日销售数据
        List<SalesVo> salesList = sellerInfoService.querySalesList(sellerId);
        data.put("salesList",salesList);
        // 新老客户信息
        int onlineNewCount = storeMemberService.onlineNewCount(sellerId.intValue());
        int offlineNewCount = storeMemberService.offlineNewCount(sellerId.intValue());
        int newCustom = onlineNewCount + offlineNewCount;
        int oldCustomer = totalCustomer - newCustom;
        CustomVo custom = new CustomVo();
        custom.setNewCustom(newCustom);
        custom.setOldCustom(oldCustomer);
        data.put("custom",custom);

        return R.ok().put("data",data);
    }

    /**
     * 紫云网审核注册商户信息
     * @param sellerInfoAuditDto
     * @return
     */
    @RequestMapping("/saveSellerInfo")
    public R saveSellerInfo(@Valid @RequestBody SellerInfoAuditDto sellerInfoAuditDto){
        return sellerInfoService.saveSellerInfo(sellerInfoAuditDto);
    }

    /**
     * 初始化商户商品
     * @return
     */
    @RequestMapping("/sellerCopyGoods")
    public R sellerCopyGoods(@RequestBody SellerCopyGoodsDto sellerCopyGoodsDto){
        return sellerInfoService.sellerCopyGoods(sellerCopyGoodsDto);
    }

    /**
     * 查询商户信息
     * @return
     */
    @RequestMapping("/info")
    public R sellerinfo(){
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        SellerInfoEntity sellerInfo = sellerInfoService.getById(sellerId);
        return R.ok().put("sellerInfo", sellerInfo);
    }

    /**
     * 查询当前登陆商户发货信息
     * @return
     */
    @RequestMapping("/queryShipInfo")
    public R queryShipInfo(){
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        SellerShipVo sellerShipVo = sellerInfoService.queryShipInfo(sellerId);
        return R.ok().put("sellerInfo", sellerShipVo);
    }

    /**
     * 初始化商户会员信息
     * @return
     */
    @RequestMapping("/initSellerMallUserId")
    public R initSellerMallUserId(@RequestParam("nums") Integer nums){
        return sellerInfoService.initSellerMallUserId(nums);
    }

}
